package dolmisani.toys.emulators.j2600.cart;

import static jstella.core.JSConstants.*;
import jstella.core.JSSystem;

/**
 * This is the standard Atari 2K cartridge. These cartridges are not
 * bankswitched, however, the data repeats twice in the 2600's 4K cartridge
 * addressing space.
 *
 * @author Bradford W. Mott
 * @version $Id: Cartridge2K.java,v 1.3 2007/08/20 05:11:26 mauvila Exp $
 */
public class Cartridge2K extends Cartridge {

    private static final long serialVersionUID = 6519396049383803731L;
    private static final int CARTRIDGE_SIZE = 2048;

    public Cartridge2K(byte[] imageBytes) {

        if (imageBytes.length != CARTRIDGE_SIZE) {
            throw new RuntimeException(
                    String.format("Invalid cartridge size %d", imageBytes.length));
        }

        md5Digest = calculateMD5Digest(imageBytes);
        cartridgeImage = toIntArray(imageBytes);
    }

    @Override
    public void install(JSSystem system) {
        this.system = system;

        // Make sure the system we're being installed in has a page size that'll work
        assert ((0x1000 & PAGE_MASK) == 0);

        addDirectPeekAccess(0x1000, 0x2000, cartridgeImage, 0x07FF);
    }

    @Override
    public int peek(int address) {
        return cartridgeImage[address & 0x07FF];
    }

    @Override
    public void poke(int address, int value) {
        // This is a ROM
    }

    @Override
    protected void setCurrentBank(int bank) {
        // Doesn't support bankswitching
    }

    @Override
    protected int getCurrentBank() {
        // Doesn't support bankswitching
        return 0;
    }

    @Override
    protected int bankCount() {
        return 1;
    }

    @Override
    public boolean patch(int address, int value) {
        cartridgeImage[address & 0x07FF] = value;
        return true;
    }
}
